package com.cqeec.controller;

import com.alibaba.fastjson.JSONObject;
import com.cqeec.util.Field;
import com.cqeec.util.GenerateXmlData;
import com.cqeec.util.MyUtil;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MainController {

    @RequestMapping("/getTablesByName")
    public List<Map> getTablesByName(String name) throws Exception {
        List<String> list=MyUtil.getTablesByName(name);
        return parseList(list);
    }

    private List<Map> parseList(List<String> list) {
        List<Map> list1=new ArrayList<>();
        for (String str:list){
            Map map=new HashMap();
            map.put("name",str);
            list1.add(map);
        }
        return list1;
    }

    @RequestMapping("/getFieldsByTableName")
    public List<Field> getFieldsByTableName(String name) throws Exception {
        return MyUtil.getFieldsByTableName(name);
    }

    @RequestMapping("/generateXML")
    public void generateXML(String resultMap, String conditions, String queryFields, String queryTables, String simpleName, HttpServletResponse response) throws Exception {
        GenerateXmlData data = new GenerateXmlData();
        data.setSimpleName(simpleName);
        data.setConditions(JSONObject.parseArray(conditions, Field.class));
        String fileName = "Extra" + simpleName + "Mapper.xml";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        OutputStream out;
        out = response.getOutputStream();
        out.write(MyUtil.generateXml(data).getBytes());
        out.flush();
        out.close();
    }

    @RequestMapping("/test01")
    public String test(){
         return "test success!";
    }


    private String parseQueryFields(String queryFields) {
        String arr[] =queryFields.split(",");
        StringBuffer sb=new StringBuffer();
        for(String str:arr){
            sb.append("        "+str+","+"\n");
        }
        String temp=sb.toString();
        return temp.substring(0,temp.lastIndexOf(","));
    }

   private  String parseQueryTable(String queryTable){
       String arr[] =queryTable.split("##");
       StringBuffer sb=new StringBuffer();
       for(String str:arr){
           sb.append("        "+str+"\n");
       }
       return sb.toString();
   }


}
